package com.itheima.ssm.controller;


import com.itheima.ssm.domain.Role;
import com.itheima.ssm.domain.UserInfo;
import com.itheima.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UsersController {

    @Autowired
    private IUserService iUserService;

    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(
            @RequestParam(name = "id",required = true)int id
    )throws Exception{
        ModelAndView mv = new ModelAndView();
//      1.根据用户的ID去查询用户
        UserInfo userInfo = iUserService.findById(id);
//      2.根据用户id查询可以添加的角色
        List<Role> otherRoles = iUserService.findOtherRoles(id);
        mv.addObject("user",userInfo);
        mv.addObject("roleList",otherRoles);
        mv.setViewName("user-role-add");
        return mv;
    }

//  给用户添加角色
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(
            @RequestParam(name = "userId",required = true)int userId,
            @RequestParam(name = "ids",required = true)int[] roleIds
    )throws Exception{
            iUserService.addRoleToUser(userId,roleIds);
            return "redirect:findAll.do";
    }

    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userList = iUserService.findAll();
        mv.addObject("userList",userList);
        mv.setViewName("user-list");
        return mv;
    }

    /**
     *@描述   添加
     *@创建人  luopengchang
     */
    @RequestMapping("/save.do")
    public String save(UserInfo info) throws Exception {
        iUserService.save(info);
        return "redirect:findAll.do";
    }

    /**
     *@描述      详情功能
     *@创建人  luopengchang
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(int id) throws Exception {
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = iUserService.findById(id);
        mv.addObject("user",userInfo);
        mv.setViewName("user-show");
        return mv;
    }
}
